package com.source.action;

import java.io.IOException;
import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.source.linkedin.Datos;
import com.source.linkedin.GeneraDocumento;
import com.source.linkedin.ObjetoLinkedIn;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.apache.struts2.ServletActionContext;
import org.scribe.exceptions.OAuthException;

public class LinkAction extends ActionSupport {

    private static final long serialVersionUID = -2613425890762568273L;
    private Map session;
    private String correo;
    private String rutaDocumento = " ";
    private String nombreDocumento;
    private String exception;
    private String exceptionStack;
    private String mensajeError;
    private ResourceBundle rbundle;

    public Map getSession() {
        return session;
    }

    public void setSession(Map session) {
        this.session = session;
    }

    public String getCorreo() {
        return correo;
    }

    public void setCorreo(String correo) {
        this.correo = correo;
    }

    public String getRutaDocumento() {
        return rutaDocumento;
    }

    public void setRutaDocumento(String rutaDocumento) {
        this.rutaDocumento = rutaDocumento;
    }

    public String getNombreDocumento() {
        return nombreDocumento;
    }

    public void setNombreDocumento(String nombreDocumento) {
        this.nombreDocumento = nombreDocumento;
    }

    public String getException() {
        return exception;
    }

    public void setException(String exception) {
        this.exception = exception;
    }

    public String getExceptionStack() {
        return exceptionStack;
    }

    public void setExceptionStack(String exceptionStack) {
        this.exceptionStack = exceptionStack;
    }

    public String getMensajeError() {
        return mensajeError;
    }

    public void setMensajeError(String mensajeError) {
        this.mensajeError = mensajeError;
    }

    public void cargaMenu() {
        session = ActionContext.getContext().getSession();
    }

    public String page01() throws OAuthException, Exception {
        cargaMenu();
        session.put("enlaceActual", "page01");
        Datos datos = new Datos();
        ObjetoLinkedIn objetoLinkedIn = new ObjetoLinkedIn();
        datos.setObjeto(objetoLinkedIn);
        session.put("datos", datos);
        HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(ServletActionContext.HTTP_RESPONSE);
        HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);

        String idioma = request.getLocale().toString();
        Locale locale = new Locale(idioma);
        rbundle = ResourceBundle.getBundle("global", locale);
        mensajeError = rbundle.getString("global.error1");
        try {
            response.sendRedirect(objetoLinkedIn.validarContraLinkedIn());
        } catch (OAuthException ex) {
            try {
                exception = ex.getMessage();
                exceptionStack = ex.toString();
                response.sendRedirect("pages/error.jsp?exception=" + exception + "&exceptionStack=" + exceptionStack + "&mensajeError=" + mensajeError);
            } catch (IOException ex1) {
                ex1.printStackTrace();
            }
        }
        // a pesar de haber un return no se ejecuta porque el sendredirect trunca la llamada a la
        // pagina seteada en struts.xml
        return "page01";
    }

    public String page02() {
        cargaMenu();
        session.put("enlaceActual", "page02");
        if (session.get("datos") != null) {
            Datos datos = (Datos) session.get("datos");
            ObjetoLinkedIn objetoLinkedIn = (ObjetoLinkedIn) datos.getObjeto();
            try {
                GeneraDocumento gd = new GeneraDocumento();
                HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
                //HttpServletResponse response = ServletActionContext	.getResponse();
                String loc = request.getLocale().toString();
                String plantillaDocumento = "";
                String tipoDocumento = request.getParameter("tipo");
                if (tipoDocumento.equals("a")) {   // clasico
                    //plantillaDocumento = "DocxCVEng.docx";
                    plantillaDocumento = "OdtCVDefault.odt";
                } else {     // formato
                    plantillaDocumento = "OdtCVEng.odt";
                    if (loc.equals("es_ES") || loc.equals("es")) {
                        plantillaDocumento = "OdtCVEsp.odt";
                    }
                    if (loc.equals("ca_ES") || loc.equals("ca")) {
                        plantillaDocumento = "OdtCVCat.odt";
                    }
                }

                ResourceBundle rbundle = ResourceBundle.getBundle("connection");
                //sc = ServletActionContext.getServletContext();
                Map<String, String> mMap = new HashMap<String, String>();
                mMap.put("pathOoo", rbundle.getString("pathOoo"));
                mMap.put("pathFisico", rbundle.getString("pathFisico"));
                mMap.put("pathServer", rbundle.getString("pathServer"));
                mMap.put("plantillaDocumento", plantillaDocumento);
                mMap.put("telefono", request.getParameter("telefono"));
                mMap.put("mail", request.getParameter("mail"));
                gd.documento(objetoLinkedIn.extraerDatos(request.getParameter("codigo")), mMap);
                rutaDocumento = rbundle.getString("pathServer") + gd.getNombreDocumento();
                nombreDocumento = gd.getNombreDocumento();
                session.put("rutaDocumento", rutaDocumento);
                session.put("nombreDocumento", nombreDocumento);
                session.put("rutaFisicaDocumento", rbundle.getString("pathFisico") + nombreDocumento);
                String idioma = request.getLocale().toString();
                Locale locale = new Locale(idioma);
                rbundle = ResourceBundle.getBundle("global", locale);
                mensajeError = rbundle.getString("global.error2");
            } catch (Exception ex) {
                try {
                    session.put("datos", null);
                    HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(ServletActionContext.HTTP_RESPONSE);
                    exception = ex.getMessage();
                    exceptionStack = ex.toString();
                    response.sendRedirect("pages/error.jsp?exception=" + exception + "&exceptionStack=" + exceptionStack + "&mensajeError=" + mensajeError);
                } catch (IOException ex1) {
                    Logger.getLogger(LinkAction.class.getName()).log(Level.SEVERE, null, ex1);
                }
            }
        } else {
            return "inicio";
        }
        return "page02";
    }

    public String page03() {
        cargaMenu();
        String rutaFisica = "";
        boolean modificado = true;
        if ((String) session.get("modificado") != null) {
            if (((String) session.get("modificado")).equals("si")) {
                modificado = false;
            }
        }

        if (modificado) {
            rutaFisica = (String) session.get("rutaFisicaDocumento");
            rutaDocumento = (String) session.get("rutaDocumento");
            nombreDocumento = (String) session.get("nombreDocumento");
        } else {
            rutaFisica = (String) session.get("rutaLoad");
            rutaDocumento = (String) session.get("rutaDocumentoUpload");
            nombreDocumento = (String) session.get("nombreDocumentoUpload");
        }
        HttpServletRequest request = ServletActionContext.getRequest();
        String file = rutaFisica;

        //destination email address
        String to = request.getParameter("tomail");

        //source email address
        String from = "curriculum@business-ecomm.com";

        //Your gmail password
        String password = "curriculum18110731";

        String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

        //hostname of the machine that has smtp server
        String host = "smtp.gmail.com";

        //either turn on or turns off debugging during sending
        boolean sessioDebug = true;


        String messageText = "<span style=\"font-family: Arial; font-weight: bold;\">Send your curriculum when you request, from any computer at any time </span>"
                + "<br style=\"font-family: Arial; font-weight: bold;\"><span style=\"font-family: Arial; font-weight: bold;\">using WebSendCV (</span>"
                + "<a style=\"font-family: Arial; font-weight: bold;\" onclick=\"onClickUnsafeLink(event);\" href=\"http://www.business-ecomm.com/WebSendCV/\" "
                + "target=\"_blank\">WebSendCV</a><span style=\"font-family: Arial; font-weight: bold;\">) </span><br>"
                + "<br><span style=\"font-family: Arial; font-weight: bold;\">Env&iacute;a tu curricular cuando te lo soliciten, desde cualquier ordenador y en cualquier momento </span>"
                + "<br style=\"font-family: Arial; font-weight: bold;\"><span style=\"font-family: Arial; font-weight: bold;\">utilizando&nbsp;</span>"
                + "<span style=\"font-family: Arial; font-weight: bold;\">WebSendCV</span><span style=\"font-family: Arial; font-weight: bold;\"> "
                + "(</span><a style=\"font-family: Arial; font-weight: bold;\" onclick=\"onClickUnsafeLink(event);\" href=\"http://www.business-ecomm.com/WebSendCV/\" "
                + "target=\"_blank\">WebSendCV</a><span style=\"font-family: Arial; font-weight: bold;\">) </span><br>"
                + "<br><span style=\"font-family: Arial; font-weight: bold;\">WebSendCV</span><span style=\"font-family: Arial; font-weight: bold;\">"
                + "&nbsp;is a tool that lets you create a word document from the data </span><br style=\"font-family: Arial; font-weight: bold;\">"
                + "<span style=\"font-family: Arial; font-weight: bold;\">that you posted on the website of LinkedIn (</span>"
                + "<a style=\"font-family: Arial; font-weight: bold;\" onclick=\"onClickUnsafeLink(event);\" href=\"http://www.linkedin.com/\" target=\"_blank\">http://www.linkedin.com/</a>"
                + "<span style=\"font-family: Arial; font-weight: bold;\">) </span><span style=\"font-family: Arial; font-weight: bold;\"></span><br>"
                + "<br><span style=\"font-family: Arial; font-weight: bold;\">WebSendCV</span><span style=\"font-family: Arial; font-weight: bold;\">"
                + "&nbsp;es una herramienta que te permite crear un documento word a partir </span><br style=\"font-family: Arial; font-weight: bold;\">"
                + "<span style=\"font-family: Arial; font-weight: bold;\">de los datos que tienes publicado en la pagina web de LinkedIn (</span>"
                + "<a style=\"font-family: Arial; font-weight: bold;\" onclick=\"onClickUnsafeLink(event);\" href=\"http://www.linkedin.com/\" target=\"_blank\">http://www.linkedin.com/</a>"
                + "<span style=\"font-family: Arial; font-weight: bold;\">) </span><br><span style=\"font-family: Arial; font-weight: bold;\"></span>"
                + "<span style=\"font-family: Arial; font-weight: bold;\"></span><br>";


        String messageSubject = nombreDocumento;

        // set the smtp host properties
        Properties props = System.getProperties();
        props.put("mail.smtp.host", host);
        props.put("mail.transport.protocol.", "smtp");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.", "true");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.put("mail.smtp.socketFactory.class", SSL_FACTORY);

        Session mailSession = Session.getInstance(props, null);
        mailSession.setDebug(sessioDebug);

        try {
            // create a message
            MimeMessage message = new MimeMessage(mailSession);

            //set message source
            message.setFrom(new InternetAddress(from));

            InternetAddress[] address = {new InternetAddress(to)};

            //set message recipients
            message.setRecipients(Message.RecipientType.TO, address);

            message.setSubject(messageSubject);

            // create and fill the first message part
            MimeBodyPart messageBodyPart1 = new MimeBodyPart();
            String htmlText = messageText;
            messageBodyPart1.setContent(htmlText, "text/html");
            // messageBodyPart1.setText(messageText);

            // create the second message part
            MimeBodyPart messageBodyPart2 = new MimeBodyPart();

            // attach the file to the message
            FileDataSource fdatasource = new FileDataSource(file);

            messageBodyPart2.setDataHandler(new DataHandler(fdatasource));
            messageBodyPart2.setFileName(fdatasource.getName());

            // create the Multipart and add its parts to it
            Multipart mpart = new MimeMultipart();
            mpart.addBodyPart(messageBodyPart1);
            mpart.addBodyPart(messageBodyPart2);

            // add the Multipart to the message
            message.setContent(mpart);

            // set the Date: header
            message.setSentDate(new Date());

            // send the message
            Transport transport = mailSession.getTransport("smtp");

            transport.connect(host, from, password);
            transport.sendMessage(message, message.getAllRecipients());

        } catch (MessagingException mex) {
            try {
                session.put("datos", null);
                HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(ServletActionContext.HTTP_RESPONSE);
                exception = mex.getMessage();
                exceptionStack = mex.toString();
                response.sendRedirect("pages/error.jsp?exception=" + exception + "&exceptionStack=" + exceptionStack + "&mensajeError=" + mensajeError);
            } catch (IOException ex) {
                Logger.getLogger(LinkAction.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return "page03";
    }

    public String page04() {
        cargaMenu();
        session.put("enlaceActual", "page04");
        return "page04";
    }
}
